<?php

use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use App\Libraries\vendor\IdentityCard;
use Illuminate\Support\Facades\Log;
use App\Model\{Config};  
use App\Model\Pm;
/**
 * 返回数组, 主要在方法中返回状态和结果集
 * 在model中处理业务时候，不仅要返回状态，还要返回状态失败的原因，因此需要返回一个数组
 * @param $status 状态0失败
 * @param $info 返回的信息
 * @param $data  返回的数据
 *---------使用方法----------------
 *  if(!$p['uid']){
 *      return msg(0,'用户iD不能为空');
 *  }
 *  $p['remarks']=$p['remarks']??'';
 *  $bool =  DB::table('moneylog')->insert($p);
 *  if($bool){
 *      return msg(1);
 *  }
 *---------------------------------
 * @author wudi
 * @return array
 */
function msg($status,$info='',$data=[]){
    return [
        'status'=>$status,
        'info'=>$info,
        'data'=>$data,
    ];
}

/**
 * 随机生成金账户流水号
 * @param $uid 可空
 */
function order_no(){
	$str = '';
	//用户uid首位末尾数字拼接
	$salt = '';
	for($i=0; $i<16; $i++){
		$salt .= rand(0,9);
	}
	return date('YmdHis').$salt;
}



/**
 * curl post 并自动跳转页面（主要用于网关页面跳转）
 * $param[url] 请求url
 * $param[data] 请求参数组成的字符串
 * $param['method'] 默认post请求
 */
function send_post_redirect($param){
	$method = isset($param['method'])?$param['method']:'post';
	$param['data'] = isset($param['data'])?$param['data']:[];
	
	$ch = curl_init ();
	curl_setopt( $ch, CURLOPT_URL,$param['url']);
	if($method=='post'){
		curl_setopt( $ch, CURLOPT_POST, 1 );
	}
	curl_setopt( $ch, CURLOPT_HEADER, 1 );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $param['data'] );
	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 30 ); // 最大连接时间
	curl_setopt( $ch, CURLOPT_TIMEOUT, 30 ); // 最大执行时间
	if(stripos($param['url'], 'https')===0){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
		curl_setopt($ch, CURLOPT_SSLVERSION, 1);
	}
	$rs = curl_exec ( $ch );
	
	if(curl_error($ch)){
		return ['response'=>'','error'=>curl_error($ch)];
	}

	$info = curl_getinfo($ch);
	if(!$info['redirect_url']){
		exit($rs);
	}  
	header('location:'.$info['redirect_url']); 
	exit;
}

/**
 * curl post 数据
 * $param[url] 请求url
 * $param[data] 请求参数组成的字符串
 * $param['method'] 默认post请求
 */
function send_post($param){
	$method = isset($param['method'])?$param['method']:'post';
	$param['data'] = isset($param['data'])?$param['data']:[];
	
	$ch = curl_init ();
	curl_setopt( $ch, CURLOPT_URL,$param['url']);
	if($method=='post'){
		curl_setopt( $ch, CURLOPT_POST, 1 );
	}
	curl_setopt( $ch, CURLOPT_HEADER, 1 );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $param['data'] );
	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 30 ); // 最大连接时间
	curl_setopt( $ch, CURLOPT_TIMEOUT, 30 ); // 最大执行时间
	if(stripos($param['url'], 'https')===0){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
		curl_setopt($ch, CURLOPT_SSLVERSION, 1);
	}
	$rs = curl_exec ( $ch );

	$body = '';
	if(curl_error($ch)){
		return ['response'=>'','error'=>curl_error($ch)];
	}
	$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
	$body = substr($rs, $headerSize);
	curl_close ( $ch );
	return $body;
}


/**
 * $param[url] 请求url
 */
function download_file($param){
	$method = isset($param['method'])?$param['method']:'post';
	$param['data'] = isset($param['data'])?$param['data']:[];
	
	$ch = curl_init ();
	curl_setopt( $ch, CURLOPT_URL,$param['url']);
	if($method=='post'){
		curl_setopt( $ch, CURLOPT_POST, 1 );
	}
	curl_setopt( $ch, CURLOPT_HEADER, 1 );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $param['data'] );
	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 30 ); // 最大连接时间
	curl_setopt( $ch, CURLOPT_TIMEOUT, 30 ); // 最大执行时间
	if(stripos($param['url'], 'https')===0){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
		curl_setopt($ch, CURLOPT_SSLVERSION, 1);
	}
	$rs = curl_exec ( $ch );
	if (is_dir($param['file_url']) || @mkdir($param['file_url'], '0777'));
	$result=file_put_contents($param['file_url'].$param['filename'].'.zip',$rs);
	curl_close ( $ch );
	return $result;
}

/**
 * 写入每日log
 * @param $msg string || array
 * @param $param['dir'] 日志的目录 默认logs目录
 * @param $param['file'] 日志文件名称
 * @return void
 * @author wudi
 */
function flog($param = []){

    $msg = $param['msg'];
    $dir = $param['dir']??$param['dir']??'';
   	$file = $param['file']??$param['file']??'log';
   	$file .= '_'.date('Ymd');

   	$temp = "--------------------------\nDate:".date('Y-m-d H:i:s')."\n";
    if(is_array($msg)){
        foreach($msg as $key=>$str){
            $temp .= $key.'=>'.$str."\n";
        }
        $msg = $temp;
    }else{
    	$msg = $temp.$msg."\n";
    }

    if($dir){
    	if( !is_dir(storage_path().'/logs/'.$dir) ){
    		mkdir (storage_path().'/logs/'.$dir, 0777, true);
    	}
    	$local_path = storage_path().'/logs/'.$dir.'/'.$file.'.log';
    }else{
    	$local_path = storage_path().'/logs/'.$file.'.log';
    }
    
    if( $handle = fopen($local_path,"a") ){
    	fwrite($handle, $msg);
    	fclose($handle);
    }
}



/**
 * 二维数组根据特定字段排序
 * @author liuchang
 * @param  Array[]  &$array
 * @param  String   $field
 * @param  boolean  $desc
 */
function sort_array_by_field(&$array, $field, $desc = true){
	$fieldArr = array();
	foreach ($array as $k => $v) {
		$fieldArr[$k] = $v[$field];
	}
	$sort = $desc ? SORT_DESC : SORT_ASC;
	array_multisort($fieldArr, $sort, $array);
}


/**
 * 生成验证码
 * @author liuchang
 */
function create_captcha($name,$prefix='md'){
	//图像处理
	$size_x = 106;
	$size_y = 38;
	$font_type = rand(1,3);
	switch($font_type){
		case 1: $font_path = public_path() . '/fonts/agenda.ttf'; break;
		case 2: $font_path = public_path() . '/fonts/honeb.ttf'; break;
		case 3: $font_path = public_path() . '/fonts/cheapfire.ttf'; break;
	}
	
	//创建图片
	$im = imagecreate($size_x,$size_y);
	imagecolorallocate($im,248,248,248);//首次使用该方法为:背景色
	$borderColor = imagecolorallocate($im,220,220,220);//边框色
	$mixColor = imagecolorallocate($im, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));//干扰颜色
	$fcolor = imagecolorallocate($im,rand(0,180),rand(0,180),rand(0,180));//字体颜色
	
	//画边框
	imageline($im,0,0,106,0,$borderColor);
	imageline($im,106,0,106,38,$borderColor);
	imageline($im,106,38,0,38,$borderColor);
	imageline($im,0,38,0,0,$borderColor);
	
	for ($i = 0; $i < 25; $i++) {
		imagesetpixel($im, mt_rand(0, $size_x), mt_rand(0, $size_y), $mixColor);//点干扰
	}
	for ($i = 0; $i < 5; $i++) {
		imagearc($im, mt_rand(-10, $size_x), mt_rand(-10, $size_y), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $mixColor);//线干扰
	}
	
	$str = '';
	for($i=0;$i<=3;$i++){
		$num = rand(0,9);//取消 dechex()10进制数转16进制
		imagettftext($im,20,rand(-15,15), (18+$i)*($i+1), 28, $fcolor, $font_path, $num);//产生验证码字符
		$str .= $num;
	}
	//将验证码存入session
	if($prefix){
		session()->put($prefix."_".$name, md5($str));
	}else{
		session()->put($name, md5($str));
	}
	session()->save();
	// header("Content-type:image/png");//定义当前页面为图像文件
	imagepng($im);                   //输出图像
	imagedestroy($im);               //销毁图像
}


/**
 * 返回JSON数据应对Ajax请求
 * @author liuchang
 * @return mix
 */
function ajaxreturn($status = 0, $info = '',$data = NULL){
	$return['data'] = $data;
	$return['status'] = $status;
	$return['info'] = $info;
	return response()->json($return);
}


/**
 * 根据源字符串和盐生成密码
 * @author liuchang
 * @param $passwd
 * @param $salt
 * @return string 40位的加密字符串
 */
function encode_passwd($passwd, $salt = '@)!#!!)@'){
	return sha1(md5($passwd) . $salt); 
}
/**
 * 能否被divided_by整除
 */
function divided_by($num,$divided_by){
    return  $num % $divided_by== 0; 
}


/**
 * 如果用户没有资金账号，给用户创建一个账号
 * @param $p['uid'] 用户id
 * @param $p['role'] 账号角色 3:余额 8：零钱，12：定存
 * @return bool
 * @author wudi
 */
function auto_create_account($p){
	$id = DB::table('user_account')->where([
			['uid','=',$p['uid']],
			['role','=',$p['role']]
		])->value('id');
	if($id>0){
		return true;
	}
	return DB::table('user_account')->insert([
			'uid'=>$p['uid'],
			'role'=>$p['role'],
		]);
}
/**
 * 根据具用户的权限菜单生产菜单url链接,
 * AdminsController.edit 转换成 admin/edit
 * @param $p string
 * @author wudi
 */
function admin_menu_url($p){
    $temp = explode('.',$p);
    $controller = str_replace('Controller','',$temp[0]);
    return $controller.'/'.$temp[1];
}
// convert a string generated with Array2String() back to the original (multidimensional) array
// usage: array String2Array ( string String)
function String2Array($String)
{
    $Return=array();
    $String=urldecode($String);
    $TempArray=explode('||',$String);
    $NullValue=urlencode(base64_encode("^^^"));
    foreach ($TempArray as $TempValue) {
        list($Key,$Value)=explode('|',$TempValue);
        $DecodedKey=base64_decode(urldecode($Key));
        if($Value!=$NullValue) {
            $ReturnValue=base64_decode(urldecode($Value));
            if(substr($ReturnValue,0,8)=='^^array^')
                $ReturnValue=String2Array(substr($ReturnValue,8));
                $Return[$DecodedKey]=$ReturnValue;
        }
        else
            $Return[$DecodedKey]=NULL;
    }
    return $Return;
}

/**
 * 在Array和String类型之间转换，转换为字符串的数组可以直接在URL上传递
 * convert a multidimensional array to url save and encoded string
 * usage: string Array2String( array Array )
 */
function Array2String($Array)
{
    $Return='';
    $NullValue="^^^";
    foreach ($Array as $Key => $Value) {
        if(is_array($Value))
            $ReturnValue='^^array^'.Array2String($Value);
        else
            $ReturnValue=(strlen($Value)>0)?$Value:$NullValue;
        $Return.=urlencode(base64_encode($Key)) . '|' . urlencode(base64_encode($ReturnValue)).'||';
    }
    return urlencode(substr($Return,0,-2)); 
}
/**
 * 管理员日志
 * @author liuchang
 * @see above
 */
function admin_log($param = []){
    $msg = $param['msg'];
    $type = $param['type'] ?? 'info';
    daily_log(['msg'=>$msg, 'path'=>'Admin', 'file'=>'admin', 'type'=>$type]);
}

/**
 * 写入每日log
 * @author liuchang
 * @param $msg string || array
 * @param type in (debug, notice, warning, error, critical, alert, emergency)
 * @return void
 */
function daily_log($param = []){
    $msg = $param['msg'];
    $path = $param['path'] ?? 'Log';
    $file = $param['file'] ?? 'Log';
    $type = $param['type'] ?? 'info';

    if(is_array($msg)){
        $temp = "\n";
        foreach($msg as $key=>$str){
            $temp .= $key.'=>'.$str."\n";
        }
        $msg = $temp;
    }
    app('log')->setDefaultDriver('daily');
    //app('log')->useDailyFiles(storage_path().'/logs/'.$path.'/'.$file.'.log');
    app('log')->$type($msg);
}

/**
 * 保留x位小数并且不进行四舍五入(floor_down别名)
 * @param float $number 数字
 * @param int $format 保留几位
 * @return string|float
 */
function sprintf_floor($number, $format = 2) {
    return (string)floor_down($number ? $number : 0, $format);
}
function floor_down($value, $places=4, $separator = "."){
    $arr =  explode($separator, $value);

    if(count($arr) != 2) {
        return $value;
    }

    $len = strlen($arr[1]);

    if ($len <= $places) {
        return $value;
    }

    $str = $arr[0] . $separator;
    for ($i=0; $i<$places; $i++) {
        $str .= $arr[1][$i];
    }
    return $str;
}

/**
 * 生成.csv文件
 * @author liuchang
 * @example
 *      make_csv([
 *          [
 *              ['a','b','c']
 *              ['aaaa','bbbb','cccc'],
 *              ['aaaa','bbbb','cccc'],
 *              ['aaaa','bbbb','cccc'],
 *              ['aaaa','bbbb','cccc'],
 *              ['啊啊啊','变变变','错错错'],
 *          ],
 *          'test' // 文件名
 *      ]);
 */
function make_csv(...$args){
    $content = '';
    foreach($args[0][0] as $v){
        $content .= @implode("\t,", (array)$v)."\t\n";
    }
    $filename = $args[0][1] ?? 'untitled';

    #$str = iconv('utf-8','GBK//IGNORE',$content);
    $str = $content;
    header("Content-type:text/csv");
    header("Content-Disposition:attachment;filename=$filename.csv");
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    die($str);
}
/**
 * csv读取
 * @param string 文件路径
 * @return array
 */
function read_csv($file){
    $file = fopen($file,'r');
    $list=[];
    while ($data = fgetcsv($file)) { 
        $arr=[];
        foreach($data as $col){ 
            try{
                $arr[]=iconv('gb2312','utf-8',$col); 
            }catch (ErrorException $e){
                $arr[]=$col;
            }
        }
        $list[] = $arr;
    }
    fclose($file);
    return $list;
}

/**
 * 获取2个日期相差的天数
 * $day1 起始日期
 * $day2 截止日期 默认当前时间
 * @author wudi
 */
function diff_day($day1,$day2=null){
    $datetime1 = new DateTime($day1);
    if($day2){
        $datetime2 = new DateTime($day2);
    }else{
        $datetime2 = new DateTime('now');
    }
    return $datetime1->diff($datetime2)->days;
}

/**
 * 金额数字标准格式化 - 小数截断,支持千分位分隔符
 * @param float $number 数字
 * @param int $decimal 保留小数位数
 * @param bool $separator 是否显示千分位分隔符
 * @return string
 */
function currency_format($number=0, $decimal=2, $separator=false) {
    $number = (float)$number;
    $number = round($number,($decimal>0?$decimal:0));
    $num = (string)$number;
    if(strstr($num, '.')){
        if($separator) {
             
            $front = strstr($num, '.', true);
            $fh = ($num < 0 && $front == 0) ? '-' : '';//防止 -0.xx  会显示为正数
             
            return $fh.number_format(strstr($num, '.', true)) . substr(rtrim(strstr($num, '.'),'.0'),0,$decimal+1);
        } else {
            return strstr($num, '.', true) . substr(rtrim(strstr($num, '.'),'.0'),0,$decimal+1);
        }
    } else {
        if($separator) {
            return number_format($num);
        } else {
            return $num;
        }
    }
}

/**
 * 获取来源页面
 * @author wudi
 */
function http_referer(){
    $redirect = "/";
    if( !empty($_SERVER['HTTP_REFERER']) && stripos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])!==false ){
        if(preg_match("#<script#i", $_SERVER['HTTP_REFERER'])){
            return false;
        }
        $redirect=$_SERVER['HTTP_REFERER'];
    }
    return urlencode($redirect);
}
/**
 * 组装和Config、User有关的数据
 * $list_array 原始数组,array类型
 * @author lizhiyu
 */
function config_collect($list_array,$table){
    $ids = [];
    $names = [];
    $config = [];
    $keys = DB::getSchemaBuilder()->getColumnListing($table);
    //获取有配置的字段
    foreach($keys as $k_keys=>$v_keys){
        $config_tmp = Config::get_config_bykey($v_keys);
        if(!empty($config_tmp)){
            $config[$v_keys] = $config_tmp;
        }
    }
    $data['config'] = $config;
    //根据配置的信息，获取其他表中$list_array需要的信息
    $id_columns=config('hengfeng_ch.id_columns');


    //获取每个元素里的id
    foreach($list_array as $k_li => $item){
        foreach($item as $k_it=>$v_it){
            if(isset($id_columns[$k_it])){
                $ids[$k_it][] = $v_it;
            }
        }
    }
    
    if(!isset($ids['channel'])){
        $ids['channel'] = [];
    }
    //得到id对应的信息
    foreach($ids as $k_ids=>$v_ids){
        //获得查询表信息
        $arr_columns = explode(':',$id_columns[$k_ids]);

        $table = $arr_columns[0];
        $namecol_arr = explode('.',$arr_columns[1]);

        //$namecol_arr[0]为主键。$namecol_arr[1]为需要的名称信息。
        if($table == 'channel'){
            $namecols = DB::table($table)->pluck($namecol_arr[1],$namecol_arr[0]);
        }else{
            $namecols = DB::table($table)->whereIn($namecol_arr[0],$v_ids)->pluck($namecol_arr[1],$namecol_arr[0]);
        }
        $names["name_".$k_ids] = $namecols;
    }
    $data['names'] = $names;
    return $data;
}

/**
 * 返回多个账户的余额
 * @param $p 二维结果集
 * @author wudi
 */
function get_account($p){
    $rs = [];
    foreach($p as $account){
        $rs[$account->uid][$account->role] = $account->balance;
    }
    return $rs;
}

//加密函数
function short_encrypt($txt,$key='midaijihua')
{
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 
    $nh = 10;
    $ch = $chars[$nh];
    $mdKey = md5($key.$ch);
    $mdKey = substr($mdKey,$nh%8, $nh%8+7);
    $txt = base64_encode($txt);
    $tmp = '';
    $i=0;$j=0;$k = 0;
    for ($i=0; $i<strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%61;
        $tmp .= $chars[$j];
    }
    return urlencode($ch.$tmp);
}
//解密函数
function short_decrypt($txt,$key='midaijihua')
{
    $txt = urldecode($txt);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    $ch = $txt[0];
    $nh = strpos($chars,$ch);
    $mdKey = md5($key.$ch);
    $mdKey = substr($mdKey,$nh%8, $nh%8+7);
    $txt = substr($txt,1);
    $tmp = '';
    $i=0;$j=0; $k = 0;
    for ($i=0; $i<strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
        while ($j<0) $j+=61;
        $tmp .= $chars[$j];
    }
    return base64_decode($tmp);
}


/**
 * 根据身份证号码获取用户地区
 * @param array $p
 *
 * $p['card'] 身份证号码|必填
 * $p['length'] 地区码长度|默认6|2省|4市|6区
 * $p['type'] 返回内容类型 'name'返回地区名称 (默认)| 'number'返回身份证地区码
 *
 * 例:get_area_by_idcard(['card'=>512501197203035172])
 *
 * @return boolean|boolean|string
 * @author zhuyiqi
 */
function get_area_by_idcard($p){
    if(!$p['card']) return false;

    if(!isset($p['length']) || !$p['length']) $p['length'] = 6;

    if(!in_array($p['length'], [2,4,6])) return false;

    if(isset($p['type']) && $p['type'] == 'number'){
        return IdentityCard::get_areanumber($p);
    }else{
        return IdentityCard::get_areaname($p);
    }
}

/**
 * 根据身份证号获取省、市、区
 * @author liuchang
 * @param String idcard
 * @param Array region
 */
function get_region_by_idcard($idcard){
    return IdentityCard::get_region($idcard);
}

/**
 * 根据身份证号获取生日
 * @author liuchang
 * @param String idcard
 * @return String YYYY-mm-dd
 */
function get_birthday_by_idcard($idcard){
    return date('Y-m-d', strtotime(IdentityCard::get_birthday($idcard)));
}

/**
 * 根据身份证号获取性别
 * @author liuchang
 * @param String idcard
 * @return int 1男 | 2女
 */
function get_gender_by_idcard($idcard){
    return IdentityCard::get_gender($idcard);
}


/**
 * 返回带星号的车牌号
 * @param string $idcard
 * @return mixed|boolean
 * @author zhuyiqi
 */
function get_fuzzy_carno($carno){
    $express = "/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/";
        
    if(!preg_match($express,$carno)){
        return substr_replace($carno,"***",5,4);
    }else{
        return false;
    }
}

/**
 * 返回带星号的身份证号码
 * @param string $idcard
 * @return mixed|boolean
 * @author zhuyiqi
 */
function get_fuzzy_idcard($idcard){
    if(strlen($idcard) == 15){
        return substr_replace($idcard,"****",8,4);
    }else if(strlen($idcard) == 18){
        return substr_replace($idcard,"************",3,11);
    }else{
        return false;
    }
}


/**
 * 返回带星号的银行卡号（只保留前4位和后4位数字）
 * @param string $bankcard 银行卡
 * @return string
 * @author zhuyiqi
 */
function get_fuzzy_bankcard($bankcard){
    $len = strlen($bankcard);
    if($len <= 8){
        $num = $len - 4;
    }else{
        $num = $len - 8;
    }
    $star = '';
    for($i = 0;$i<$num;$i++){
        $star .= '*';
    }
    return substr_replace($bankcard,$star,4,$num);
}

/**
 * 返回带星号的手机号（只保留前3位和后4位数字）
 * @param string $phone 手机号
 * @return string
 * @author zhuyiqi
 */
function get_fuzzy_phone($phone){
	return substr($phone, 0, 3).'****'.substr($phone, 7);
}



/**
 * 截取分行名称
 * @param string $name 分行全称
 * @return string
 * @author zhuyiqi
 */
function get_fenhang_name($name){

    if(strpos($name,'公司') !== false){
        preg_match("/公司(?<right>.*)/", $name, $matches);
        return $matches[1];
    }else if(strpos($name,'银行') !== false){
        preg_match("/银行(?<right>.*)/", $name, $matches);
        return $matches[1];
    }else{
        return $name;
    }
}



/**
 * 获取带星号的名字（只显示姓）
 * @param string $real_name 名字
 * @return string 例：张**
 * @author zhuyiqi
 */
function get_fuzzy_name($real_name){
    $name = splitName($real_name);
    $len = mb_strlen($name[1],'utf-8');
    $second_name = '';
    for ($i=0;$i<$len;$i++){
        $second_name .= '*';
    }
    return $name[0].$second_name;
}
/**
 * 拆分姓和名
 * @param string $fullname 名字
 * @return array   [0=>'姓',1=>'名']
 * @author zhuyiqi
 */
function splitName($fullname){
    $hyphenated = array('欧阳','太史','端木','上官','司马','东方','独孤','南宫','万俟','闻人','夏侯','诸葛','尉迟','公羊','赫连','澹台','皇甫',
        '宗政','濮阳','公冶','太叔','申屠','公孙','慕容','仲孙','钟离','长孙','宇文','城池','司徒','鲜于','司空','汝嫣','闾丘','子车','亓官',
        '司寇','巫马','公西','颛孙','壤驷','公良','漆雕','乐正','宰父','谷梁','拓跋','夹谷','轩辕','令狐','段干','百里','呼延','东郭','南门',
        '羊舌','微生','公户','公玉','公仪','梁丘','公仲','公上','公门','公山','公坚','左丘','公伯','西门','公祖','第五','公乘','贯丘','公皙',
        '南荣','东里','东宫','仲长','子书','子桑','即墨','达奚','褚师');
    $vLength = mb_strlen($fullname, 'utf-8');
    $lastname = '';
    $firstname = '';//前为姓,后为名
    if($vLength > 2){
        $preTwoWords = mb_substr($fullname, 0, 2, 'utf-8');//取命名的前两个字,看是否在复姓库中
        if(in_array($preTwoWords, $hyphenated)){
            $lastname = $preTwoWords;
            $firstname = mb_substr($fullname, 2, 10, 'utf-8');
        }else{
            $lastname = mb_substr($fullname, 0, 1, 'utf-8');
            $firstname = mb_substr($fullname, 1, 10, 'utf-8');
        }
    }else if($vLength == 2){//全名只有两个字时,以前一个为姓,后一下为名
        $lastname = mb_substr($fullname ,0, 1, 'utf-8');
        $firstname = mb_substr($fullname, 1, 10, 'utf-8');
    }else{
        $lastname = $fullname;
    }
    return array($lastname, $firstname);
}  
/**
 * 高精度运算
 * @author liuchang
 * @param  array  $p    参与运算的数值数组
 * @param  string $type sub:减法 | add:加法
 * @param  number $len  保留小数位数
 * @return number
 */
function bc_all($p, $len=2, $type='sub'){
    $num = 0;
    if(is_array($p)) foreach($p as $k=>$v){
        if($k==0){
            $num = $v;
            continue;
        }
        switch($type){
            case 'sub':
                $num = bcsub($num, $v, $len);
                break;
            case 'add':
                $num = bcadd($num, $v, $len);
                break;
        }
    }
    return $num;
}
/**
 * 单个数字变汉字
 * @param int $x  1,2,3....
 * @return string 一，二，三....
 * @author zhuyiqi
 */
function n2c($x){
    $arr_n = array("零","一","二","三","四","五","六","七","八","九","十");
    return $arr_n[$x];
}


/**
 * 在缓存中取出统计数字
 * @param string $key  
 * @return number
 * @author lizhiyu
 */

function cache_statistics($key){
    $minutes = 24*60;
    switch($key){
    	case 'total_investor'://累计投资人
            $res = Cache::remember($key,$minutes,function () {
                //return DB::table('user')->where('is_invest',1)->count();
            	return DB::table('user')->count('id');
            });
            break;
    	case 'total_benefit'://累计收益
            $res = Cache::remember($key,$minutes,function () {
                return DB::table('borrow_repay_loan')->where('freeze_status',0)->sum('interest');
            });
            break;
        case 'deposit_sum'://定存成交总额
            $res = Cache::remember($key,$minutes,function () {
                return DB::table('borrow')->whereIn('borrow_status',[1,2,3])->sum('already_money');
            });
            break;
        case 'trad_sum_buy'://交易总额
            $res = Cache::remember($key,$minutes,function () {
                return DB::table('trad')->where('cancel_status',0)->sum('buy_amount');
            });
            break;
        case 'account_wallet'://余额总额
            $res = Cache::remember($key,$minutes,function () {
                return DB::table('user_account')->where('role',3)->sum('balance');
            });
            break;
        case 'holding_deposit_sum'://新定存当前持有额
        	$res = Cache::remember($key,$minutes,function () {
        		return DB::table('borrow_repay')->where('transfer_status',0)->sum('total');
        	});
        	break;
        case 'bid_count'://债权总数
        	$res = Cache::remember($key,$minutes,function () {
        		return DB::table('borrow')->whereIn('borrow_status',[1,2,3])->count();
        	});
        	break;
        case 'old' : //老系统首页统计数据     (数据结构 '首页累计交易额-首页累计收益-定存数据')
        	$res = Cache::remember($key,$minutes,function () {
        		$old = get_old_cache_statistics();
        		return implode('-', $old);
        	});
        default:
    }
    return $res;
}


/**
 * 解析老系统首页统计数据
 * @return mixed
 * @author zhuyiqi
 */
function explode_old_cache_statistics(){
	$old = cache_statistics('old');
	$data = explode('-', $old);
	$rs['total'] = $data[0];
	$rs['total_income'] = $data[1];
	$rs['holding_deposit'] = $data[2]; //TODO 应该取迁移当天持有的数据，之后就不变了（迁移进来的持有状态的定存数据）
	return $rs;
}

/**
 * 修改老系统用户信息
 * @param array $data
 * $data['uid'] 用户uid 不为空时update 为空时insert
 * 其他数据参考老系统
 *
 * @author zhuyiqi
 */
function set_old_sync_user($data){
    // 同步用户注册
    $data['key'] = hash("sha256", implode("",$data).'FIv5GY85A0yXWyCvXlsvqUYX8BIaRn3X6UKbcraUmZo=');
    return send_post([
        'data' => $data,
        'url' => config('web.sync_user')
    ]);
}
/**
 * 生成随即字符串
 * @author youjiahua
 * @param string type
 * @param int length
 */
function random_string($type = 'alnum', $len = 8){
    switch($type){
        case 'basic'    :
            return mt_rand();
            break;
        case 'alnum'    :
        case 'numeric'  :
        case 'nozero'   :
        case 'alpha'    :
        case 'captcha'  :
            switch ($type){
                case 'alpha'    :   $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
                case 'alnum'    :   $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
                case 'numeric'  :   $pool = '0123456789';
                break;
                case 'nozero'   :   $pool = '123456789';
                break;
                case 'captcha'  :   $pool = '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ';
                break;
            }
            $str = '';
            for ($i=0; $i < $len; $i++){
                $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
            }
            return $str;
            break;
        case 'unique'   :
        case 'md5'      :
            return md5(uniqid(mt_rand()));
            break;
    }
}




/**
 * 金额数组递归格式化
 * @author liuchang
 * @see above
 */
function currency_all($value, $decimal, $separator){
    if(is_array($value)){
        foreach($value as &$v){
            $v = currency_all($v, $decimal, $separator);
        }
        unset($v);
        return $value;
    }else{
        return is_intstr($value) ? currency_format($value, $decimal, $separator) : 0;
    }
}

/**
 * 判断是否int或int类型的字符
 * @author liuchang
 * @param String | Number
 * @return bool
 */
function is_intstr($value) {
    return is_int($value) || ( (is_string($value)||is_float($value)) && preg_match('/^\d+([.]\d+)?$/', $value) );
}


/**
 * 获取老系统零钱数据
 * @param int $uid  用户uid
 * @return array 
 * [
 * 		'can_redeem' 零钱可赎回份额 
 * 		'all'        零钱总资产
 * ]
 * @author zhuyiqi
 */
function get_old_lingqian($uid){
	$url = config('web.lingqian_data').$uid;
	$data = json_decode(send_post([
			'url' => $url,
	]), true);
	return $data['data'];
}


/**
 * 获取老系统首页统计数据
 * @return array
 * [
 * 		'total' 首页累计交易额
 * 		'total_income'   首页累计收益
 * 		'holding_deposit' 定存数据
 * ]
 * @author zhuyiqi
 */
function get_old_cache_statistics(){
	$url = config('web.cache_statistics');
	$data = json_decode(send_post([
			'url' => $url,
	]), true);
	return $data['data'];
}


/**
 * 格式化账单的时间
 * @param $time_str string 时间
 * @return string $str
 * @author zhuyiqi
 */
function format_bill_time($time_str) {
	$time = strtotime($time_str);
	
	$date = date("Y-m-d", $time);
	$today = date("Y-m-d");
	$yesterday = date("Y-m-d",strtotime("-1 day"));
	if($today == $date) {
		// 今日
		return date("H:i", $time);
	} else if($yesterday == $date) {
		// 昨日
		return '昨天'.date("H:i", $time);
	} else {
		$arr = explode('-', $date);
		$year = $arr[0];
		
		$arr = explode('-', $today);
		$this_year = $arr[0];
		if ($year == $this_year) {
			// 今年
			return date("m-d", $time);
		} else {
			// 往年
			return $date;
		}
	}
}



/**
 * 是否需要显示资产迁移说明
 * @param 用户uid $uid
 * @return boolean true 显示     | false 不显示
 * @author zhuyiqi
 */
function show_intro_alert($uid){
	$intro_pm_id = current(Config::get_config_bykey('intro_pm_id'));
	$last_old_id = current(Config::get_config_bykey('last_old_uid'));
	if($uid <= $last_old_id){
		$pm = DB::table('pm')->where(['pid'=>$intro_pm_id,'to_uid'=>$uid,'is_read'=>1])->exists();
		if($pm){
			return false;
		}else{
			return true;
		}
	}else{
		Pm::read_pm($intro_pm_id, $uid);//新用户直接设为已读
		return false;
	}
	
}

function html($str){
    return htmlspecialchars($str,null,null,false);
}

/**
 * 把二维数组中摸个字段作为key
 * $key 字段
 * 返回多数组
 */
function arrays_set_key($array,$key,$std = true){
    if(empty($array)){
        return [];
    }
    $rs = [];
    if( $std ==true ){
        foreach($array as $r){
            $rs[$r->$key] = $r;
        }
        return $rs;
    }
    foreach($array as $r){
        $rs[$r[$key]][] = $r;
    }
    return $rs;
}

/**
 * 获取一维数组中多个字段值的集合
 * $keys array 字段集合
 * 
 */
function array_multiple_column($array,$keys){
    $rs = [];
    foreach($keys as $key){
        if(isset($array[$key])){
            $rs[] = $array[$key];
        }
    }
    return $rs;
}

function get_array_keys($array,$key,$std=true){
    $data = [];
    foreach($array as $item){
        $data[] = $item->$key;
    }
    return $data;
}

function last_url($id){
    $url = $_SERVER['REQUEST_URI'];
    if(preg_match('#profile#i', $url)){
        return false;
    }
    $c = explode('/',$url);
    if(count($c)==3){
        Cache::set('admin:menu:key:'.$id, $url ,100);
    }
}

function img($url){
    if(stripos($url, 'http')===0){
        return $url;
    }
    return '/'.ltrim($url,'/');
}

/**
 * 给文件名加后缀
 */
function suffix($file,$suffix){
    if(empty($file)) return '';
    $info = pathinfo($file);
    return $info['dirname'].'/'.$info['filename'].$suffix.'.'.$info['extension'];
}